"""pytest 配置文件"""
import pytest
import tempfile
import os
from app import create_app
from app.extensions import db
from app.models import User


@pytest.fixture(scope='session')
def app():
    """创建测试应用实例"""
    # 创建临时数据库文件
    db_fd, db_path = tempfile.mkstemp()
    
    # 设置测试配置
    test_config = {
        'TESTING': True,
        'SQLALCHEMY_DATABASE_URI': f'sqlite:///{db_path}',
        'WTF_CSRF_ENABLED': False,
        'SECRET_KEY': 'test-secret-key',
        'JWT_SECRET_KEY': 'test-jwt-secret-key'
    }
    
    app = create_app()
    
    # 更新配置
    app.config.update(test_config)
    
    with app.app_context():
        db.create_all()
        yield app
        db.drop_all()
    
    os.close(db_fd)
    os.unlink(db_path)


@pytest.fixture
def client(app):
    """创建测试客户端"""
    return app.test_client()


@pytest.fixture
def runner(app):
    """创建测试CLI运行器"""
    return app.test_cli_runner()


@pytest.fixture
def test_user(app):
    """创建测试用户"""
    with app.app_context():
        user = User(
            username='testuser',
            email='test@example.com',
            first_name='Test',
            last_name='User'
        )
        user.password = 'password123'
        db.session.add(user)
        db.session.commit()
        return user


@pytest.fixture
def admin_user(app):
    """创建管理员用户"""
    with app.app_context():
        admin = User(
            username='admin',
            email='admin@example.com',
            first_name='Admin',
            last_name='User',
            is_admin=True
        )
        admin.password = 'admin123'
        db.session.add(admin)
        db.session.commit()
        return admin


@pytest.fixture
def auth_headers(client, test_user):
    """获取认证头"""
    response = client.post('/api/v1/auth/login', json={
        'username': test_user.username,
        'password': 'password123'
    })
    token = response.get_json()['data']['access_token']
    return {'Authorization': f'Bearer {token}'}


@pytest.fixture
def admin_headers(client, admin_user):
    """获取管理员认证头"""
    response = client.post('/api/v1/auth/login', json={
        'username': admin_user.username,
        'password': 'admin123'
    })
    token = response.get_json()['data']['access_token']
    return {'Authorization': f'Bearer {token}'} 